#include "svd.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>

void matrix_from_file(struct matrix_t *mat, const char *file)
{
    FILE *fp;
    int h, w;
    fp = fopen(file, "r");
    // 读取元数据
    fscanf(fp, "%d", &h);
    fscanf(fp, "%d", &w);
    //读数据
    init_matrix(mat, h, w, PRIMARY);
    
    for (int i = 0; i < w; i++)
        for (int j = 0; j < h; j++)
            fscanf(fp, "%lf", &mat->in[i + j * h]);
    fclose(fp);
    mat->h = h;
    mat->w = w;
}

/*把矩阵写入文件*/
void matrix_to_file(struct matrix_t mat, const char *file)
{
    FILE *fp;
    int w = mat.w;
    int h = mat.h;
    if ((fp = fopen(file, "w")) == NULL)
    {
        perror("fopen");
        exit(1);
    }
    fprintf(fp, "%d\t%d\n", w, h); //文件首行记录矩阵的行数和列数
    int i, j;
    for (i = 0; i < w; ++i)
    {
        for (j = 0; j < h; ++j)
        {
            fprintf(fp, "%-10f\t", mat.out[i + j * h]);
        }
        fprintf(fp, "\n");
    }
    fclose(fp);
}

/*把向量写入文件*/
void vector_to_file(REAL *vector, int len, const char *file)
{
    FILE *fp;
    if ((fp = fopen(file, "w")) == NULL)
    {
        perror("fopen");
        exit(1);
    }
    int i;
    for (i = 0; i < len; ++i)
    {
        fprintf(fp, "%-10f\t", vector[i]);
    }
    fclose(fp);
}